package com.hlf.modules.merchant.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.hlf.common.constants.Constants;
import com.hlf.common.constants.FileConstants;
import com.hlf.common.exception.BusinessException;
import com.hlf.common.utils.*;
import com.hlf.modules.api.entity.UserStore;
import com.hlf.modules.api.mapper.UserStoreMapper;
import com.hlf.modules.merchant.bank.entity.BankCard;
import com.hlf.modules.merchant.bank.mapper.BankCardMapper;
import com.hlf.modules.merchant.goods.entity.Goods;
import com.hlf.modules.merchant.goods.entity.GoodsType;
import com.hlf.modules.merchant.goods.mapper.GoodsMapper;
import com.hlf.modules.merchant.goods.mapper.GoodsTypeMapper;
import com.hlf.modules.merchant.merchant.entity.Merchant;
import com.hlf.modules.merchant.merchant.service.MerchantService;
import com.hlf.modules.merchant.store.entity.Store;
import com.hlf.modules.merchant.store.entity.XdLInfo;
import com.hlf.modules.merchant.store.mapper.StoreMapper;
import com.hlf.modules.merchant.store.mapper.XdLInfoMapper;
import com.hlf.modules.merchant.store.service.StoreService;
import com.hlf.modules.sys.entity.File;
import com.hlf.modules.sys.entity.SysUserEntity;
import com.hlf.modules.sys.mapper.AreaMapper;
import com.hlf.modules.sys.mapper.SysUserMapper;
import com.hlf.modules.sys.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("storeService")
public class StoreServiceImpl implements StoreService {
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private GoodsTypeMapper goodsTypeMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private FileService fileService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private BankCardMapper bankCardMapper;
    @Autowired
    private PropertieUtil propertieUtil;
    @Autowired
    private UserStoreMapper userStoreMapper;
    @Autowired
    private XdLInfoMapper xdLInfoMapper;

    /**
     * 修改店铺时查询单个
     * (门店地址已截取)
     *
     * @param id
     * @return
     */
    @Override
    public Store queryObject(Long id) {
        Store store = storeMapper.queryObject(id);
        List<File> logoList = fileService.select(FileConstants.LOGO_IMG, id);
        store.setLogoImg(logoList);
        store = subAddress(store);
        return store;
    }

//    /**
//     * 查询单个店铺
//     *
//     * @param id
//     * @return
//     */
//    @Override
//    public Store queryObject(Long id) {
//        Store store = storeMapper.queryObject(id);
//        BankCard bankCard = bankCardMapper.findListbyStoreId(id);
//        List<File> identityList = fileService.select(FileConstants.IDENTITY_CARD_IMG, id);
//        List<File> bussinessList = fileService.select(FileConstants.BUSINESS_IMG, id);
//        List<File> openList = fileService.select(FileConstants.OPEN_ACCOUNT_LICENSE_IMG, id);
//        List<File> logoList = fileService.select(FileConstants.LOGO_IMG, id);
//        String[] identity = new String[2];
//        for (int i = 0; i < identityList.size(); i++) {
//            identity[i] = identityList.get(i).getFilSerPath();
//        }
////        File bussinessFile = bussinessList.size() > 0 ? bussinessList.get(0) : null;
////        File openFile = openList.size() > 0 ? openList.get(0) : null;
////        File logoFile = logoList.size() > 0? logoList.get(0) : null;
//        store.setBankCard(bankCard);
////        store.setIdentity(identity);
////        store.setBussiness(bussinessFile == null ? null : bussinessFile.getFilSerPath());
////        store.setOpen(openFile == null ? null : openFile.getFilSerPath());
//        store.setLogoImg(logoList);
//
//        return store;
//    }

    @Override
    public List<Store> queryList(Map<String, Object> map) {
        return storeMapper.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return storeMapper.queryTotal(map);
    }

    /**
     * 插入非空
     * 创建店铺,默认创建 商品类型分类
     *
     * @param store
     */
    @Transactional
    @Override
    public String saveStore(Store store) {
        //返回判断
        String flag = null;
        //保存门店
        storeMapper.insertSelective(store);

        //创建默认商品类型
        GoodsType goodsType = new GoodsType();
        goodsType.setStoreId(store.getId());
        goodsType.setInsertBy(store.getInsertBy());
        String[] goodsTypes = {"招牌菜", "凉菜", "热菜", "饮料"};
        for (String type : goodsTypes) {
            goodsType.setId(IdWorkerFactory.nextId());
            goodsType.setName(type);
            goodsTypeMapper.insertSelective(goodsType);
        }

        //创建茶位费
        Integer defaultTeaPrice = Constants.DEFAULT_TEA_PRICE;
        Goods goods = new Goods();
        goods.setId(IdWorkerFactory.nextId());
        goods.setMerchantId(store.getMerchantId());
        goods.setStoreId(store.getId());
        goods.setName("茶位费");
        goods.setGoodsType(Constants.DEFAULT_TEA_GOODS_TYPE);
        goods.setNum(IdWorkerFactory.nextId());
        goods.setSellPrice(defaultTeaPrice);
        //茶位费库存
        goods.setInitQty(99999);
        goods.setRemainQty(99999);
        goods.setInsertBy(store.getUserId());
        goods.setDailyStock(Constants.GOODS_DAILY_STOCK_OPEN);

        goodsMapper.insertSelective(goods);

        //user表填充storeId
        Long id = store.getId();
        Long userId = store.getUserId();

        if (userId == null) {
            throw new BusinessException("userId为空!");
        }

        SysUserEntity sysUserEntity = sysUserMapper.queryObject(userId);
        String storeIdStr = String.valueOf(id);
        String currentStoreId = sysUserEntity.getCurrentStoreId();
        if (currentStoreId == null || currentStoreId.length() == 0) {
            //修改当前门店id
            sysUserEntity.setCurrentStoreId(storeIdStr);
            //修改返回标志位
            flag = storeIdStr;
        }
        String storeIds = sysUserEntity.getStoreIds();

        //拼接
        if (storeIds == null || storeIds.length() == 0) {
            storeIds = storeIdStr + "/";
        } else {
            storeIds = storeIds + storeIdStr + "/";
        }
        sysUserEntity.setStoreIds(storeIds);
        //执行修改
        sysUserMapper.updateByPrimaryKeySelective(sysUserEntity);

        //返回标志位
        return flag;
    }

    /**
     * 创建门店
     *
     * @return
     */
    @Override
    @Transactional
    public ReturnResult createStore(Store store, List<File> logoImg, SysUserEntity user) {

        //商家id
        String storeId = user.getCurrentStoreId();
        Long merchantId = storeMapper.queryObject(storeId).getMerchantId();
        //加入商家id
        store.setMerchantId(merchantId);

        Merchant merchant = merchantService.queryObject(merchantId);
        Long userId = merchant.getUserId(); //获取userId
        long id = IdWorkerFactory.nextId();
        //保存图片

        for (File img : logoImg) {
            img.setInsertBy(userId);
            img.setForeignId(id);
        }
        fileService.inserts(logoImg);
        store.setId(id);
        store.setUserId(userId);
        store.setMerchantId(merchantId);
        store.setSoftwareStatus(Constants.SOFTWARE_PAY_STATUS_TRY);
        store.setExpiryDate(DateUtil.addDay(new Date(), Integer.parseInt(propertieUtil.getPropertie("SOFT_FREE_DAYS"))));

        //生成地址
        store = buildAddress(store);
        //保存店铺
        saveStore(store);

        //保存门店与用户之间关系
        UserStore userStore = new UserStore();
        userStore.setId(IdWorkerFactory.nextId());
        userStore.setUserId(user.getUserId());
        userStore.setUserName(user.getUsername());
        userStore.setName(user.getName());
        userStore.setStoreId(id);
        userStore.setMobile(user.getMobile());
        userStore.setRoleId(Constants.ROLE_ID_MERCHANT);
        userStore.setInsertByUserName(user.getUsername());
        userStore.setInsertDate(new Date());
        userStoreMapper.insert(userStore);
        return ReturnResult.ok();
    }

    /**
     * 修改认证门店,保存相关照片,保存银行卡信息
     *
     * @param user
     * @param store
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAuthStore(SysUserEntity user, Store store) {
        Long userId = user.getUserId();
        Long id = store.getId();
        Long bankCardId ;
        BankCard bankCardQuery = bankCardMapper.findListbyStoreId(id);
        if (bankCardQuery == null) {
            BankCard bankCard = store.getBankCard();
            bankCardId = IdWorkerFactory.nextId();
            bankCard.setId(bankCardId);
            bankCard.setInsertBy(userId);
            bankCard.setStoreId(id);
            bankCard.setLastUpdateBy(userId);
            bankCardMapper.insertSelective(bankCard);
        } else {
            BankCard bankCard = store.getBankCard();
            bankCardId = bankCard.getId();
            bankCard.setId(bankCardQuery.getId());
            bankCard.setLastUpdateBy(userId);
            bankCardMapper.updateByPrimaryKeySelective(bankCard);
        }
        store.setLastUpdateDate(new Date());
        store.setLastUpdateBy(userId);
        store = buildAddress(store);
        store.setProfitBankCardId(bankCardId);
        storeMapper.updateByPrimaryKeySelective(store);

        List<File> businessImg = store.getBusinessImg();
        List<File> bankCardImg = store.getBankCardImg();
        List<File> identityCardImg = store.getIdentityCardImg();
        List<File> openLicenseImg = store.getOpenLicenseImg();
        List<File> storeSignImg = store.getStoreSignImg();

        List<File> idCardList = fileService.select(FileConstants.IDENTITY_CARD_IMG, id);
        List<File> bankCardList = fileService.select(FileConstants.BANK_CARD_IMG, id);
        List<File> storeSignList = fileService.select(FileConstants.STORE_SIGN_IMG, id);
        List<File> openList = fileService.select(FileConstants.OPEN_ACCOUNT_LICENSE_IMG, id);
        List<File> businessImgList = fileService.select(FileConstants.BUSINESS_IMG, id);

        if (businessImg.size() + businessImgList.size() > 1) {
            throw new BusinessException("营业执照照片最多只能有一张!");
        }
        if (bankCardImg.size() + bankCardList.size() > 2) {
            throw new BusinessException("银行卡照片最多只能有两张!");
        }
        if (identityCardImg.size() + idCardList.size() > 2) {
            throw new BusinessException("身份证照片最多只能有两张!");
        }
        if (openList.size() + openLicenseImg.size() > 1) {
            throw new BusinessException("开户许可证照片最多只能有一张!");
        }
        if (storeSignImg.size() + storeSignList.size() > 3) {
            throw new BusinessException("门店照片最多只能有三张!");
        }

        for (File file : storeSignImg) {
            file.setForeignId(id);
            file.setLastUpdateBy(userId);
        }
        for (File file : openLicenseImg) {
            file.setForeignId(id);
            file.setLastUpdateBy(userId);
        }
        for (File file : identityCardImg) {
            file.setForeignId(id);
            file.setLastUpdateBy(userId);
        }
        for (File file : bankCardImg) {
            file.setForeignId(id);
            file.setLastUpdateBy(userId);
        }
        for (File file : businessImg) {
            file.setForeignId(id);
            file.setLastUpdateBy(userId);
        }

        fileService.inserts(businessImg);
        fileService.inserts(bankCardImg);
        fileService.inserts(identityCardImg);
        fileService.inserts(openLicenseImg);
        fileService.inserts(storeSignImg);

    }

    @Override
    public List<Store> queryListByReview(Byte auditStatusReview) {
        return storeMapper.queryListByReview(auditStatusReview);
    }

    @Override
    public BankCard getBankCard(Long storeId) {
        BankCard bankCardQuery = bankCardMapper.findListbyStoreId(storeId);
        return bankCardQuery;
    }

    /**
     * 拼接地址
     *
     * @param store
     * @return
     */
    private Store buildAddress(Store store) {
        String provinceStr = null;
        String cityStr = null;
        String districtStr = null;
        Long province = store.getProvince();
        Long city = store.getCity();
        Long district = store.getDistrict();
        String address = store.getAddress();
        if (province != null) {
            provinceStr = areaMapper.selectByAreaCode(province).getName();
        }
        if (city != null) {
            cityStr = areaMapper.selectByAreaCode(city).getName();
        }
        if (district != null) {
            districtStr = areaMapper.selectByAreaCode(district).getName();
        }
        //详细地址
        address = provinceStr + cityStr + districtStr + address;
        store.setAddress(address);
        return store;
    }

    /**
     * 截取地址
     *
     * @param store
     * @return
     */
    private Store subAddress(Store store) {

        String address = "";
        address = address + areaMapper.selectByAreaCode(store.getProvince()).getName();
        address = address + areaMapper.selectByAreaCode(store.getCity()).getName();
        address = address + areaMapper.selectByAreaCode(store.getDistrict()).getName();
        store.setAddress(store.getAddress().substring(address.length()));
        return store;
    }

    /**
     * 门店列表
     *
     * @param
     * @return
     */
    @Override
    public List<Store> queryListForMerchantId(Long merchantId) {
        return storeMapper.queryListForMerchantId(merchantId);
    }

    /**
     * 修改门店信息
     */
    @Override
    @Transactional
    public void updateInfo(SysUserEntity user, Store store) {
        Long userId = user.getUserId();
        store.setLastUpdateBy(userId);
        store = buildAddress(store);
        List<File> logoImg = store.getLogoImg();
        for (File img : logoImg) {
            img.setInsertBy(userId);
            img.setForeignId(store.getId());
            File file = fileService.selectById(img.getFilId());
            if (file == null) {
                Long id = IdWorkerFactory.nextId();
                img.setFilId(id);
                fileService.insert(img);
            }
        }

        int i = storeMapper.updateByPrimaryKeySelective(store);
        if (i == 0) {
            throw new BusinessException("修改失败!");
        }
    }

    /**
     * 上传门店形象照片
     *
     * @param user
     * @param storeImgFilesJson
     */
    @Override
    public void uploadStore(SysUserEntity user, String storeImgFilesJson) {
        Long userId = user.getUserId();
        String storeId = user.getCurrentStoreId();
        //保存图片
        List<File> storeImgs;
        if (storeImgFilesJson != null && storeImgFilesJson.length() > 0) {
            storeImgs = JSON.parseArray(storeImgFilesJson, File.class);

            //校验门店形象照数量
            List<File> files = fileService.select(FileConstants.STORE_IMG, Long.parseLong(storeId));
            int i = files.size() + storeImgs.size();
            if (i > Integer.valueOf(propertieUtil.getPropertie("STORE_IMG_NUMBER"))) {
                throw new BusinessException("照片数量过多!");
            }
            for (File storeImg : storeImgs) {
                storeImg.setInsertBy(userId);
                storeImg.setForeignId(Long.parseLong(storeId));
            }
            fileService.inserts(storeImgs);
        }
    }

//    /**
//     * 保存门店认证信息
//     */
//    public void saveStoreDetail(Store store,List<File> idCardImg, List<File> businessImg, List<File> openImg ,SysUserEntity user) {
//        Long profitBankCardId = IdWorkerFactory.nextId();
//        Long userId = user.getUserId();
//        Long storeId = Long.parseLong(user.getCurrentStoreId());
//
//        Store storeQuery = storeMapper.queryObject(storeId);
//        Byte auditStatus = storeQuery.getAuditStatus();
//        if (Constants.AUDIT_STATUS_PASS.equals(auditStatus)) {
//            throw new BusinessException("审核已通过!");
//        }
//        Store store = new Store();
//        store.setLastUpdateBy(userId);
//        store.setId(storeId);
//        store.setMerchantName(merchantName);
//        store.setLegalperson(legalPerson);
//        store.setLicense(license);
//        store.setAuditStatus(Constants.AUDIT_STATUS_REVIEW);
//        store.setProfitBankCardId(profitBankCardId);
//
//        int j = storeMapper.updateByPrimaryKeySelective(store);
//        if (j == 0) {
//            throw new BusinessException("认证失败!");
//        }
//        //保存身份证照片
//        saveImg(storeId, userId, identityCardImgJson);
//        //保存营业执照
//        saveImg(storeId, userId, businessImg);
//        //保存食品经营许可证照片
//        saveImg(storeId, userId, qsImg);
//        //保存开户许可证
//        saveImg(storeId, userId, openAccountLicenseImg);
//        //银行卡信息
//        BankCard bankCard = new BankCard();
//        bankCard.setId(profitBankCardId);
//        bankCard.setUserId(userId);
//        bankCard.setStoreId(storeId);
//        bankCard.setBranchBankId(Integer.valueOf(branchBankId));  //支行id
//        bankCard.setProvince(Long.parseLong(province));
//        bankCard.setCity(Long.parseLong(city));
//        bankCard.setDistrict(Long.parseLong(district));
//        bankCard.setBankName(bankName);
//        bankCard.setBranchBankName(branchBankName);
//        bankCard.setCardNo(cardNo);
//        bankCard.setAccountName(accountName);
//        bankCard.setType(Integer.valueOf(type));
//        bankCard.setInsertBy(userId);
//        bankCard.setLastUpdateBy(userId);
//        int i = bankCardMapper.insertSelective(bankCard);
//        if (i == 0) {
//            throw new BusinessException("认证失败!");
//        }
//    }

    /**
     * 门店形象
     *
     * @param user
     * @return
     */
    @Override
    public ReturnResult storeImg(SysUserEntity user) {
        List<File> fileList = fileService.select(FileConstants.STORE_IMG, Long.parseLong(user.getCurrentStoreId()));
        return ReturnResult.ok().put(Constants.DEFAULT_RESULT_NAME, fileList);
    }


    @Override
    public void update(Store store) {
        storeMapper.updateByPrimaryKeySelective(store);
    }

    @Override
    public void save(Store store) {
        storeMapper.save(store);
    }

    @Override
    public void delete(Long id) {
        storeMapper.delete(id);
    }

    @Override
    public void deleteBatch(Long[] ids) {
        storeMapper.deleteBatch(ids);
    }

    /**
     * 分页查询
     */
    @Override
    public PageUtils queryListForPage(Map<String, Object> map) {
        Query query = new Query(map);
        int total = storeMapper.queryTotal(query);
        List<Store> storeList = null;
        if (total > 0) {
            storeList = storeMapper.queryList(query);
            for (Store store : storeList) {
                XdLInfo xdLInfo = xdLInfoMapper.selectByPrimaryKey(store.getId());
                if (xdLInfo!=null){
                    store.setUpMercId(xdLInfo.getMercId());
                }
                List<File> select = fileService.select(FileConstants.LOGO_IMG, store.getId());
                File file = null;
                if (select.size() > 0) {
                    file = select.get(0);
                }
                if (file == null) {
                    continue;
                }
                store.setUrl(file.getFilSerPath());
            }
        }
        return new PageUtils(storeList, total, query.getLimit(), query.getPage());
    }

    /**
     * 根据当前门店高管userId查店铺
     *
     * @param userId
     * @return
     */
    @Override
    public Store queryObjectForUserId(Long userId) {
        return storeMapper.queryObjectForUserId(userId);
    }

    /**
     * 保存图片
     */
    public void saveImg(Long foreignId, Long userId, String imgsJson) {
        //保存图片
        List<File> imgList;
        if (imgsJson != null && imgsJson.length() > 0) {
            imgList = JSON.parseArray(imgsJson, File.class);
            for (File img : imgList) {
                img.setInsertBy(userId);
                img.setForeignId(foreignId);
            }
            fileService.inserts(imgList);
        }
    }


}
